#!/bin/bash

# ============================================
# Web3管理平台 - 快速安装脚本 (轻量版)
# 仅安装核心依赖，快速部署
# ============================================

set -e

readonly GREEN='\033[0;32m'
readonly BLUE='\033[0;34m'
readonly YELLOW='\033[1;33m'
readonly NC='\033[0m'

echo -e "${BLUE}"
echo "╔════════════════════════════════════════════════════════╗"
echo "║              Web3管理平台 - 快速安装                  ║"
echo "║              ⚡ 轻量版本，3分钟完成                   ║"
echo "╚════════════════════════════════════════════════════════╝"
echo -e "${NC}"

# 快速配置检测
INSTALL_DIR="./web3-management"
SERVICE_USER="root"
USE_SUDO=""

if [[ $EUID -ne 0 ]]; then
    INSTALL_DIR="/home/$USER/web3-management"
    SERVICE_USER=$USER
    USE_SUDO="sudo"
fi

echo "📍 安装目录: $INSTALL_DIR"

# 快速依赖检查
check_dependencies() {
    echo "⚡ 快速检查依赖..."

    # 检查Docker
    if ! command -v docker &> /dev/null; then
        echo "❌ Docker未安装，请先安装Docker"
        echo "快速安装: curl -fsSL https://get.docker.com | sh"
        exit 1
    fi

    # 检查Docker Compose
    if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
        echo "❌ Docker Compose未安装"
        exit 1
    fi

    # 启动Docker（如果未启动）
    if ! docker info &> /dev/null; then
        echo "🔧 启动Docker..."
        $USE_SUDO systemctl start docker || true
    fi

    echo "✅ 依赖检查完成"
}

# 快速下载项目
download_project() {
    echo "📥 下载项目文件..."

    $USE_SUDO rm -rf $INSTALL_DIR
    $USE_SUDO mkdir -p $INSTALL_DIR

    # 快速克隆（仅下载最新代码，不包含历史）
    $USE_SUDO git clone --depth 1 --single-branch https://gitee.com/0616_652/web3_management.git $INSTALL_DIR

    # 设置权限
    if [[ $EUID -eq 0 ]]; then
        chown -R root:root $INSTALL_DIR
    else
        $USE_SUDO chown -R $SERVICE_USER:$SERVICE_USER $INSTALL_DIR
    fi

    echo "✅ 项目下载完成"
}

# 快速配置生成
generate_config() {
    echo "⚙️  生成配置..."

    # 使用简化配置
    cat > $INSTALL_DIR/.env << EOF
# Web3管理平台 - 快速配置
MYSQL_ROOT_PASSWORD=123456
MYSQL_USER=web3user
MYSQL_PASSWORD=123456
JWT_SECRET=web3-jwt-secret-$(date +%s)
JWT_EXPIRATION=86400
LOG_LEVEL=INFO
SHOW_SQL=false
TZ=Asia/Shanghai
EOF

    echo "✅ 配置生成完成"
}

# 快速启动服务
start_services() {
    echo "🚀 启动服务..."

    cd $INSTALL_DIR

    # 直接启动，无需预拉取镜像
    if [[ $EUID -eq 0 ]]; then
        docker-compose up -d
    else
        $USE_SUDO -u $SERVICE_USER docker-compose up -d
    fi

    echo "✅ 服务启动中..."
}

# 快速健康检查
quick_health_check() {
    echo "🔍 快速健康检查..."

    # 等待MySQL
    echo -n "等待MySQL"
    for i in {1..15}; do
        if docker exec web3-mysql mysqladmin ping -h localhost -u root -p123456 &> /dev/null; then
            echo " ✅"
            break
        fi
        echo -n "."
        sleep 2
    done

    # 等待后端
    echo -n "等待后端"
    for i in {1..20}; do
        if curl -s http://localhost:8080/actuator/health &> /dev/null; then
            echo " ✅"
            break
        fi
        echo -n "."
        sleep 2
    done

    echo "✅ 服务就绪"
}

# 创建快速管理脚本
create_quick_script() {
    echo "📝 创建管理脚本..."

    $USE_SUDO tee /usr/local/bin/web3 > /dev/null << 'EOF'
#!/bin/bash
cd $(dirname $(find /opt /home -name "docker-compose.yml" -path "*/web3-management/*" 2>/dev/null | head -1))
case ${1:-status} in
    start)   docker-compose up -d ;;
    stop)    docker-compose down ;;
    restart) docker-compose restart ;;
    status)
        docker-compose ps
        echo ""
        echo "访问地址: http://$(hostname -I | awk '{print $1}'):80"
        ;;
    logs)    docker-compose logs -f ${2:-} ;;
    update)
        git pull
        docker-compose up -d --build
        ;;
    *) echo "用法: $0 {start|stop|restart|status|logs|update}" ;;
esac
EOF

    $USE_SUDO chmod +x /usr/local/bin/web3
    echo "✅ 管理脚本已创建 (使用 'web3' 命令)"
}

# 显示完成信息
show_completion() {
    clear
    echo -e "${GREEN}"
    echo "╔══════════════════════════════════════════════════════════╗"
    echo "║                🎉 快速安装完成！                         ║"
    echo "╚══════════════════════════════════════════════════════════╝"
    echo -e "${NC}"

    local server_ip=$(hostname -I | awk '{print $1}')
    echo "🌐 访问地址: http://$server_ip"
    echo "🔧 API地址:  http://$server_ip:8080"
    echo "👤 默认账号: admin / admin123"
    echo "🔑 数据库密码: 123456"
    echo ""
    echo "⚡ 快速命令:"
    echo "  web3 status    # 查看状态"
    echo "  web3 logs      # 查看日志"
    echo "  web3 restart   # 重启服务"
    echo "  web3 update    # 更新系统"
    echo ""
    echo "📁 安装路径: $INSTALL_DIR"
}

# 主安装流程（简化版）
main() {
    echo "🚀 开始快速安装..."

    check_dependencies
    download_project
    generate_config
    start_services
    quick_health_check
    create_quick_script
    show_completion

    echo ""
    echo -e "${YELLOW}💡 提示: 如需完整功能，请运行 ./install.sh${NC}"
}

# 错误处理
trap 'echo -e "\n❌ 安装失败"; exit 1' ERR

# 执行主流程
main "$@"
